using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;
using MReviewerClient.MReviewerSvc;
using MReviewerClient.Providers;

namespace MReviewerClient.Models
{
    /// <summary>
    /// The model of EstablishmentType
    /// </summary>
    public class EstablishmentTypeModel
    {
        #region Fields

        /// <summary>
        /// The collection of EstablishmentType
        /// </summary>
        public ObservableCollection<EstablishmentTypeDTO> EstablishmentTypes;

        /// <summary>
        /// The object for synchronization
        /// </summary>
        private static object syncLock = new object();

        /// <summary>
        /// The instance of EstablishmentTypeModel
        /// </summary>
        private static EstablishmentTypeModel instance;

        /// <summary>
        /// The singleton instance
        /// </summary>
        public static EstablishmentTypeModel Instance
        {
            get
            {
                lock (syncLock)
                {
                    if (instance == null)
                        instance = new EstablishmentTypeModel();
                    return instance;
                }
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Select all of the EstablishmentType
        /// </summary>
        public void SelectAll()
        {
            // The action is invoke when the operation is complete
            EventHandler<EstablishmentType_SelectAllCompletedEventArgs> handler = null;
            handler = (s, e) =>
            {
                this.EstablishmentTypes = e.Result;
                MReviewerService.Instance.EstablishmentType_SelectAllCompleted -= handler;
            };
            // Read all of the establishment
            MReviewerService.Instance.EstablishmentType_SelectAllCompleted += handler;
            MReviewerService.Instance.EstablishmentType_SelectAllAsync();
        }

        /// <summary>
        /// Select an EstablishmentType by ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public EstablishmentTypeDTO SelectByID(int id)
        {
            return this.EstablishmentTypes.FirstOrDefault(n => n.ID == id);
        }

        /// <summary>
        /// Get Index from id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int GetIndexFromID(int id)
        {
            return this.EstablishmentTypes.IndexOf(
                this.EstablishmentTypes.FirstOrDefault(n => n.ID == id));
        }

        #endregion
    }
}